//
//  Importer.m
//  iBioCAD
//
//  Created by Orbitus on 10/4/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "Importer.h"
#import "iBioCAD_Controller.h"

@implementation Importer

- (id) managedObjectModel
{
	id highlightDocument = [myDocController currentDocument];
	return [highlightDocument managedObjectModel];
}
- (id) managedObjectContext
{
	id highlightDocument = [myDocController currentDocument];
	return [highlightDocument managedObjectContext];
}
- (void)setInstallationFolderPath:(id)path;
{
	installPath = [[path copy] autorelease];
	NSLog(@"*******installPath = %@",installPath);
}

- (void) awakeFromNib
{

	
	
	NSMOCDidChangeNotification = [NSNotification notificationWithName:@"NSMOCDidChangeNotification" object:nil];
	[@"" writeToFile:@"/Sequences/iBioCAD/Desktop/sequence.fasta" atomically:YES encoding:NSUTF8StringEncoding error:nil];
	myDocController = [NSDocumentController sharedDocumentController];
	myDocs = [myDocController documents];
	
	if ([myDocs count] == 0)
	{
		[myDocController openUntitledDocumentAndDisplay:YES error:nil];
	}
	highlightDocument = [myDocController currentDocument];
	managedObjectContext = [highlightDocument managedObjectContext];
	managedObjectModel = [highlightDocument managedObjectModel];
	
	
	entities = [managedObjectModel entitiesByName];
	
	uceEntity = [entities valueForKey:@"UCE"];
	ncuEntity = [entities valueForKey:@"NCU"];
	cddEntity = [entities valueForKey:@"CDD"];
	blocksEntity = [entities valueForKey:@"Blocks"];
	clusterEntity = [entities valueForKey:@"Cluster"];
	proteinEntity = [entities valueForKey:@"Protein"];
	monomerEntity = [entities valueForKey:@"Monomer"];
	dnaEntity = [entities valueForKey:@"DNA"];
	mRNAEntity = [entities valueForKey:@"MRNA"];
	aminoacidEntity = [entities valueForKey:@"AminoAcid"];
	atomEntity = [entities valueForKey:@"Atom"];
	
	ncuSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	ncuSortDescriptors = [NSArray arrayWithObject: ncuSort];
	ncuFetch = [[NSFetchRequest alloc] init];
	[ncuFetch setEntity: ncuEntity];
	[ncuFetch setSortDescriptors: ncuSortDescriptors];
	
	cddSortName = [[NSSortDescriptor alloc] initWithKey:@"ncuID" ascending:YES];
	cddSortProtStart = [[NSSortDescriptor alloc] initWithKey:@"protStart" ascending:YES];
	cddSortDescriptors = [NSArray arrayWithObjects: cddSortName, cddSortProtStart,nil];
	cddFetch = [[NSFetchRequest alloc] init];
	[cddFetch setEntity: cddEntity];
	[cddFetch setSortDescriptors: cddSortDescriptors];
	
	uceSortName = [[NSSortDescriptor alloc] initWithKey:@"ncuID" ascending:YES];
	uceSortProtStart = [[NSSortDescriptor alloc] initWithKey:@"protStart" ascending:YES];
	uceSortDescriptors = [NSArray arrayWithObjects:uceSortName, uceSortProtStart,nil];
	uceFetch = [[NSFetchRequest alloc] init];
	[uceFetch setEntity: uceEntity];
	[uceFetch setSortDescriptors: uceSortDescriptors];
	
	blocksSortName = [[NSSortDescriptor alloc] initWithKey:@"ncuID" ascending:YES];
	blocksSortProtStart = [[NSSortDescriptor alloc] initWithKey:@"protStart" ascending:YES];
	blocksSortDescriptors = [NSArray arrayWithObjects: blocksSortName, blocksSortProtStart,nil];
	blocksFetch = [[NSFetchRequest alloc] init];
	[blocksFetch setEntity: blocksEntity];
	[blocksFetch setSortDescriptors: blocksSortDescriptors];
	
	clusterSort = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
	clusterSortDescriptors = [NSArray arrayWithObject: clusterSort];
	clusterFetch = [[NSFetchRequest alloc] init];
	[clusterFetch setEntity: clusterEntity];
	[clusterFetch setSortDescriptors: clusterSortDescriptors];
	
	proteinSort = [[NSSortDescriptor alloc] initWithKey:@"codeName" ascending:YES];
	proteinSortDescriptors = [NSArray arrayWithObject: proteinSort];
	proteinFetch = [[NSFetchRequest alloc] init];
	[proteinFetch setEntity: proteinEntity];
	[proteinFetch setSortDescriptors: proteinSortDescriptors];
	
	monomerSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	monomerSortDescriptors = [NSArray arrayWithObject: monomerSort];
	monomerFetch = [[NSFetchRequest alloc] init];
	[monomerFetch setEntity: monomerEntity];
	[monomerFetch setSortDescriptors: monomerSortDescriptors];
	
	dnaSort = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
	dnaSortDescriptors = [NSArray arrayWithObject: dnaSort];
	dnaFetch = [[NSFetchRequest alloc] init];
	[dnaFetch setEntity: dnaEntity];
	[dnaFetch setSortDescriptors: dnaSortDescriptors];
	
	mRNASort = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
	mRNASortDescriptors = [NSArray arrayWithObject: mRNASort];
	mRNAFetch = [[NSFetchRequest alloc] init];
	[mRNAFetch setEntity: mRNAEntity];
	[mRNAFetch setSortDescriptors: mRNASortDescriptors];
	
	aminoacidSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	aminoacidSortDescriptors = [NSArray arrayWithObject: aminoacidSort];
	aminoacidFetch = [[NSFetchRequest alloc] init];
	[aminoacidFetch setEntity: aminoacidEntity];
	[aminoacidFetch setSortDescriptors: aminoacidSortDescriptors];
	
	atomSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	atomSortDescriptors = [NSArray arrayWithObject: atomSort];
	atomFetch = [[NSFetchRequest alloc] init];
	[atomFetch setEntity: atomEntity];
	[atomFetch setSortDescriptors: atomSortDescriptors];
	
	
}
- (void)finishedDownload:(NSNotification *)aNotification {
	int status = [[aNotification object] terminationStatus];
    if (status == 1)
        NSLog(@"Task succeeded.");
    else
        NSLog(@"Task failed.");
}
-(IBAction)test:(id)sender
{
	NSLog(@"install location from Importer:   %@",installPath);
}

- (int) openDNA:(id)myFilePath
{

	[[NSNotificationCenter defaultCenter] postNotificationName:@"NSMOCDidChangeNotification" object: nil];

	int returncount = 0;
	int pleaseDeleteConvertedFile = 0;
	NSString *fileLocationToParse = [myFilePath objectAtIndex:0];

	
//	NSLog(@"1open %@",[highlightDocument description]);
	
//	highlightDocument = [myDocController currentDocument];

//	[highlightDocument applySpeedometerSettings:self];
	
	if ([pathExtension compare: @"fasta" ] != 0)
	{
		pleaseDeleteConvertedFile = 1;
		//Remember to change myFilePath to the fasta file
		//Go through EMBOSS's seqret!~ for each file in myFilePath
		//NSLog(pathExtension);
		
		// Upon opening a file: start with EMBL -> FASTA
		// check if its a multiple alignment already
		// if so split the files out into individual ones....well do the alignments ourselves
		//   based on any data we see in our original.
		// create an NSTask in order to seqret our file and return just the fasta stuff to stdout?
		// when we have the data lets then 	
		NSString *installLocationFilePath = [[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent]
											 stringByAppendingPathComponent:@"installLocation.txt"];
		id installationLocation = @"";
		id fileManager = [NSFileManager defaultManager];

		
		if ( [fileManager fileExistsAtPath:installLocationFilePath isDirectory:NULL] ) {
			installationLocation = [NSString stringWithContentsOfFile:installLocationFilePath];
		}
		
	
		
		NSBundle*	myBundle	= [NSBundle mainBundle];
		NSString*	myAppPath	= [myBundle bundlePath];
		NSString*	myAppFolderPath	= [myAppPath stringByDeletingLastPathComponent];
		NSString*	seqretPath	= [installationLocation stringByAppendingString:@"/Applications/EMBOSS-5.0.0/emboss/seqret"];
		NSLog(@"Your Task Path %@",seqretPath);
		
		NSTask *seqret = [[NSTask alloc] init];
		NSPipe *pipe = [[NSPipe alloc] init];
		NSFileHandle *handle;
		
		[seqret	setLaunchPath:seqretPath];
		[seqret setCurrentDirectoryPath:[[myFilePath objectAtIndex:0] stringByDeletingLastPathComponent]];
		NSMutableArray* seqretArguments = [[NSMutableArray alloc]	init];
		[seqretArguments addObject:@"-sequence"];
		[seqretArguments addObject:[myFilePath objectAtIndex:0]];
		[seqretArguments addObject:@"-osf"];
		[seqretArguments addObject:@"fasta"];
		[seqretArguments addObject:@"-outseq"];
		[seqretArguments addObject:[[myFilePath objectAtIndex:0] stringByAppendingString:@".fasta"]];
		[seqretArguments addObject:@"-auto"];	
		[seqret setArguments:seqretArguments];
		[seqret setStandardOutput:pipe];

		fileLocationToParse = [[myFilePath objectAtIndex:0] stringByAppendingString:@".fasta"];
		 //[[[[[[[[myFilePath objectAtIndex:0] path] stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"desktop"] stringByAppendingPathComponent:[[something objectAtIndex:0] name] ] stringByAppendingString:@".fasta"];

		myFilePath = [NSArray arrayWithObject:[[myFilePath objectAtIndex:0] stringByAppendingString:@".fasta"]];
		pathExtension = @"fasta";
		
		[seqret launch];
		[seqret terminate];
		[seqret release];
		
		//Do some parsing of the EMBL data structure.....go ahead and put the DNA into the MOC....
		//WE can just adjust the DNA live as the Official Multiple alignment window requests for and
		//Changes to be notified so he can redraw!
		
		//The preview window becomes a sort of easy way to translucently change the DNA as its imported.....maybe
		//we can overlay the images and show off some cool shit by closing the current window but keeping the 
		//modified DNA line....
		
		/*Thanks. I had actually read that, and it wasn't quite what I was looking for. Anyway, I figured it out :). You can bind instance variables of the front most document using the keypath "mainWindow.windowController.document.relevantObjectController" with a binding to Shared Application. Put the NSObjectController(s) in the MyDocument nib and set MyDocument to have outlets to them with proper methods so that they can be accessed using Key-Value Coding/Observing and everything works great. I sure do like Bindings, they're just a little hard to figure out how exactly to use sometimes.*/
		
		
		//Here is the way we do it with MOC and MOM
	}
	if ([pathExtension compare: @"fasta" ]==0)
	{
		//Do normal DNA READ and insert into MOC
		//Loop through each file in myFilePath
		
		

		[mySystemMessages setStringValue:@"Starting Import"];
		int i;
	//	NSScanner *theScanner;
		NSString *line,*sequenceString;
		NSMutableArray *ncuLines;
		NSMutableArray *blocksLines;
		NSMutableArray *cddLines;
		NSMutableArray *uceLines;
		char string [200];
		sequenceString  = @"";
		
		sequenceString = [[NSString alloc] init]; 					
		ncuLines = [[NSMutableArray alloc] init];					
		blocksLines = [[NSMutableArray alloc] init];					
		cddLines = [[NSMutableArray alloc] init];					
		uceLines = [[NSMutableArray alloc] init];					
		
		 
		 
		 //NSMutableArray *dnaLines;
		 
		 
		// FILE * ff= fopen([fileLocationToParse UTF8String ],"r") ;
		 sequenceString  = @"";
		 					
	

		FILE * ncu		= fopen([[myFilePath objectAtIndex:0] UTF8String],"r") ;
		
	//	id tabSet = [NSCharacterSet characterSetWithCharactersInString:@"\t"];
		
		//NCU FILE FIRST
		if (ncu == NULL) {
			fprintf(stderr,"***  Unable to open file, returning NULL! *** \n");
		} else {
			char *sa;
			sa 	= fgets (string, 200, ncu);
			while( sa!= NULL)
			{
				[ncuLines addObject: [[[NSString alloc] initWithUTF8String:sa] uppercaseString]] ;			
				sa 	= fgets (string, 200, ncu);
			}
			fclose(ncu);
		}
	
		[mySystemMessages setStringValue:@"Done Reading... Processing Data..."];
		NSLog(@"Done Reading... Processing Data...");
		
		if (pleaseDeleteConvertedFile == 1)
			[[NSFileManager defaultManager] removeFileAtPath:[myFilePath objectAtIndex:0] handler:nil];
		
		NSString *myString = [NSString stringWithContentsOfFile:@"/Sequences/iBioCAD/Desktop/sequence.fasta"];
		int first = 1;
		id newNCU;
		for ( i=0; i < [ncuLines count]; i++)
		{
			line = [ncuLines objectAtIndex:i];
			if ([line hasPrefix:@">"])  {
				returncount++;
				int control=0;
				id line2 = [ncuLines objectAtIndex:i+1];
				{
					int j;
					for (j = 0; j < [line2 length]; j++)
					{
						control += [line2 rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"bdefhijklmnopqrsuvwxyzBDEFHIJKLMNOPQRSUVWXYZ"]].length;
						//id temp = [line2 substringWithRange:NSMakeRange(j, 1)]
						//if ([temp caseInsensitiveCompare:@"a"] ||;
					}
				}
				if (control/[line2 length]*100 > 20 ) // is 20% of our string Protein
				{
					newNCU = [NSEntityDescription insertNewObjectForEntityForName:@"Protein" inManagedObjectContext:managedObjectContext];
				}
				else
				{
					newNCU = [NSEntityDescription insertNewObjectForEntityForName:@"DNA" inManagedObjectContext:managedObjectContext];

				}

				
				
				
				
				[newNCU setValue:@"" forKey:@"sequence"];
				[newNCU setValue:[line stringByReplacingOccurrencesOfString:@"\n" withString:@""] forKey:@"title"];
				if (first != 1)
				{
					myString = [myString stringByAppendingString:@"\n"];
				}				
				myString = [myString stringByAppendingString:[@">" stringByAppendingString:[line stringByReplacingOccurrencesOfString:@">" withString:@"" ]]];

				first = 0;
			}
			else
			{
				[newNCU setValue:[[newNCU valueForKey:@"sequence"] stringByAppendingString:[line stringByReplacingOccurrencesOfString:@"\n" withString:@""]] forKey:@"sequence"];
				myString = [myString stringByAppendingString:[line stringByReplacingOccurrencesOfString:@"\n" withString:@""]];
				//[newNCU setValue:[[newNCU valueForKey:@"sequence"] stringByAppendingString:[[line stringByReplacingOccurrencesOfString:@"\n" withString:@""] stringByReplacingOccurrencesOfString:@"*" withString:@"" ]] forKey:@"sequence"];
				
			}
		}
		
		[myString writeToFile:@"/Sequences/iBioCAD/Desktop/sequence.fasta" atomically:YES encoding:NSUTF8StringEncoding error:nil];
		
		
		
		
		
	}
	NSLog(@"Finished");
	return returncount;
}
- (int) openProtein:(id)myFilePath
{
	
	[[NSNotificationCenter defaultCenter] postNotificationName:@"NSMOCDidChangeNotification" object: nil];
	int i;
	NSString *aName = @"name";
	NSString *resName = @"resname";
	NSString *chain = @"a";
	NSString *xchar = @"x";
	float aNumber;
	float resNum;
	float x;
	float y;
	float z;
	float occ;
	float b;
	NSString *line,*sequenceString;
	char string [200];
	
	FILE * ff= fopen([[myFilePath objectAtIndex:0] UTF8String ],"r"); 
	FILE * atomFile = fopen([[[myFilePath objectAtIndex:0] stringByAppendingString:@"output.atoms"] UTF8String ],"w");

	NSScanner * theScanner;
	sequenceString  = @"";
	
	if (ff == NULL) {
		fprintf(stderr,"***  Unable to open file, returning NULL! *** \n");
	} else {
		char *sa;
		sa 	= fgets (string, 200, ff);
		
		double atomCount = 0;
		
		id sequenceString = [[NSString alloc] init]; 					
		id pdbLines = [[NSMutableArray alloc] init];					
		

		id newProtein = [NSEntityDescription insertNewObjectForEntityForName:@"Protein"
																	 inManagedObjectContext:managedObjectContext];
		id newMonomer;// = [NSEntityDescription insertNewObjectForEntityForName:@"Monomer"
		//inManagedObjectContext:managedObjectContext];
		//id newAA = [NSEntityDescription insertNewObjectForEntityForName:@"AminoAcid"
		//inManagedObjectContext:managedObjectContext];
		int	jj;
		id atoms = [[NSMutableArray alloc] init];
		id monomers = [[NSMutableArray alloc] init];
		id residues = [[NSMutableArray alloc] init];
		int prevResNum = 0;
		
		id prevRes = nil;
		id prevChain = @"O";
		id newAtom;
		id newAA;
		
		id newHelix;
		id newSheet;
		//id newAtom = [NSEntityDescription insertNewObjectForEntityForName:@"Atom"
		//inManagedObjectContext:managedObjectContext];
		[newProtein setValue:@"" forKey:@"header"];
		[newProtein setValue:@"" forKey:@"title"];
		[newProtein setValue:@"" forKey:@"compound"];
		[newProtein setValue:@"" forKey:@"source"];
		[newProtein setValue:@"" forKey:@"keyWords"];
		[newProtein setValue:@"" forKey:@"experimentalData"];
		[newProtein setValue:@"" forKey:@"author"];
		[newProtein setValue:@"" forKey:@"revData"];
		[newProtein setValue:@"" forKey:@"journal"];
		[newProtein setValue:@"" forKey:@"remarks"];
		[newProtein setValue:@"" forKey:@"advancingSequence"];
		[newProtein setValue:@"" forKey:@"residueSequence"];
		[newProtein setValue:@"" forKey:@"modifiedSequence"];
		
		
		
		[newProtein setValue:[[[myFilePath objectAtIndex:0]  lastPathComponent] stringByDeletingPathExtension] forKey:@"codeName"];
		//id subunitA = [NSEntityDescription insertNewObjectForEntityForName:@"ProteinSunUnit"
		//inManagedObjectContext:managedObjectContext];
		//id amino1 = [NSEntityDescription insertNewObjectForEntityForName:@"AminoAcid"
		//inManagedObjectContext:managedObjectContext];
		//id atom1 = [NSEntityDescription insertNewObjectForEntityForName:@"Atom"
		//inManagedObjectContext:managedObjectContext];
		//NSLog(@"entities:%@", [entities description]);
		
		
		singleLetter = [[NSDictionary alloc] initWithObjectsAndKeys:
						@"G", @"GLY", 
						@"A", @"ALA", 
						@"V", @"VAL", 
						@"L", @"LEU", 
						@"I", @"ILE", 
						@"F", @"PHE", 
						@"M", @"MET", 
						@"P", @"PRO", 
						@"W", @"TRP", 
						@"S", @"SER", 
						@"T", @"THR", 
						@"Y", @"TYR", 
						@"C", @"CYS", 
						@"N", @"ASN", 
						@"Q", @"GLN", 
						@"D", @"ASP", 
						@"E", @"GLU", 
						@"H", @"HIS", 
						@"K", @"LYS", 
						@"R", @"ARG", nil];
		
		
		fullName = [[NSDictionary alloc] initWithObjectsAndKeys:
					@"Glycine", @"GLY", 
					@"Alanine", @"ALA", 
					@"Valine", @"VAL", 
					@"Leucine", @"LEU", 
					@"Isoleucine", @"ILE", 
					@"Phenylalanine", @"PHE", 
					@"Methionine", @"MET", 
					@"Proline", @"PRO", 
					@"Tryptophan", @"TRP", 
					@"Serine", @"SER", 
					@"Threonine", @"THR", 
					@"Tyrosine", @"TYR", 
					@"Cystine", @"CYS", 
					@"Asparagine", @"ASN", 
					@"Glutamine", @"GLN", 
					@"Asparatic Acid", @"ASP", 
					@"Glutamic Acid", @"GLU", 
					@"Histidine", @"HIS", 
					@"Lysine", @"LYS", 
					@"Arginine", @"ARG", nil];
		
		
		while( sa!= NULL)
		{
			//printf("%s",sa);
			[pdbLines addObject: [[[NSString alloc] initWithUTF8String:sa] uppercaseString]];
			sa 	= fgets (string, 200, ff);
		}
		fclose(ff) ; //Close with an NSMutableArray of NSStrings called pdbLines
		
		//NSLog(@"Your log entry:%@", [pdbLines description]); //  This line makes sure we have pdbLines correctly initialized
		
		
		
		for ( i=0; i < [pdbLines count]; i++)
		{
			line = [pdbLines objectAtIndex:i];
			if ( [line hasPrefix:@"HEADER"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"header"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"header"];
			}
			if ( [line hasPrefix:@"TITLE"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"title"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"title"];
			}
			if ( [line hasPrefix:@"COMPND"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"compound"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"compound"];
			}
			if ( [line hasPrefix:@"SOURCE"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"source"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"source"];
			}
			if ( [line hasPrefix:@"KEYWDS"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"keyWords"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 60)]] forKey:@"keyWords"];
			}
			if ( [line hasPrefix:@"EXPDTA"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"experimentalData"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"experimentalData"];
			}
			if ( [line hasPrefix:@"AUTHOR"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"author"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"author"];
			}
			if ( [line hasPrefix:@"REVDAT"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"revData"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"revData"];
			}
			if ( [line hasPrefix:@"JRNL"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"journal"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"journal"];
			}
			if ( [line hasPrefix:@"REMARK"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"remarks"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"remarks"];
			}
			if ( [line hasPrefix:@"SEQADV"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"advancingSequence"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"advancingSequence"];
				//[newMonomer setValue:[[newMonomer valueForKey:@"advancingSequence"] stringByAppendingString:[line substringWithRange:NSMakeRange(10, 70)]] forKey:@"advancingSequence"];
			}
			if ( [line hasPrefix:@"SEQRES"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"residueSequence"] stringByAppendingString:[line substringWithRange:NSMakeRange(19, 52)]] forKey:@"residueSequence"];
				//[newMonomer setValue:[[newMonomer valueForKey:@"residueSequence"] stringByAppendingString:[line substringWithRange:NSMakeRange(19, 52)]] forKey:@"residueSequence"];
			}
			
			if ( [line hasPrefix:@"MODRES"] )
			{
				[newProtein setValue:[[newProtein valueForKey:@"modifiedSequence"] stringByAppendingString:[line substringWithRange:NSMakeRange(19, 52)]] forKey:@"modifiedSequence"];
				//[newMonomer setValue:[[newMonomer valueForKey:@"modifiedSequence"] stringByAppendingString:[line substringWithRange:NSMakeRange(19, 52)]] forKey:@"modifiedSequence"];
			}
			if ( [line hasPrefix:@"HELIX"] )
			{
				newHelix = [NSEntityDescription insertNewObjectForEntityForName:@"Helix"
																			  inManagedObjectContext:managedObjectContext];
				
				[newHelix setValue:[line substringWithRange:NSMakeRange(11, 11)] forKey:@"startAA"];
				[newHelix setValue:[line substringWithRange:NSMakeRange(22, 12)] forKey:@"endAA"];
				[newHelix setValue: newProtein forKey:@"protein"];
				[[newProtein mutableSetValueForKey:@"helices"] addObject:newHelix];
				
			}
			if ( [line hasPrefix:@"SHEET"] )
			{
				id newSheet = [NSEntityDescription insertNewObjectForEntityForName:@"Sheet"
																				 inManagedObjectContext:managedObjectContext];
				
				[newSheet setValue:[line substringWithRange:NSMakeRange(11, 70)] forKey:@"line"];
				[newSheet setValue: newProtein forKey:@"protein"];
				[[newProtein mutableSetValueForKey:@"sheets"] addObject:newSheet];
				
			}
			
			
			if ([line hasPrefix:@"ATOM"])
			{
				
				newAtom = [NSEntityDescription insertNewObjectForEntityForName:@"Atom"
																			 inManagedObjectContext:managedObjectContext];
				
				[atoms addObject: newAtom];
				
				
				theScanner = [NSScanner scannerWithString:[line substringWithRange:NSMakeRange(6, 6)]];		
				[theScanner scanFloat:&aNumber];
				[newAtom setValue:[NSNumber numberWithFloat:aNumber] forKey:@"number"];
				
				theScanner = [NSScanner scannerWithString:[line substringWithRange:NSMakeRange(12, 3)]];	
				aName = [line substringWithRange:NSMakeRange(13, 3)];
				//NSLog(@"%@, ----%@",[fullName description], [singleLetter description]);
				[newAtom setValue:aName forKey:@"name"];
				
				
				
				theScanner = [NSScanner scannerWithString:[line substringWithRange:NSMakeRange(22, 4)]];	
				[theScanner scanFloat:&resNum];
				[newAtom setValue:[NSNumber numberWithFloat:resNum] forKey:@"resNum"];
				
				theScanner = [NSScanner scannerWithString:[line substringWithRange:NSMakeRange(16, 1)]];	
				resName = [line substringWithRange:NSMakeRange(17, 3)];
				[newAtom setValue:resName forKey:@"resName"];
				
				/*
				if (!(resNum == prevResNum)){
					prevResNum = resNum;
					newAA = [NSEntityDescription insertNewObjectForEntityForName:@"AminoAcid"
																				  inManagedObjectContext:managedObjectContext];
					[residues addObject:newAA];
					[newAA setValue:[NSNumber numberWithFloat:resNum] forKey:@"number"];
					//[[newProtein mutableSetValueForKey:@"aminoAcids"] addObject: newAA];
					//[newAA setValue:newProtein forKey:@"protein"];
					
					[newAA setValue:resName forKey:@"codon"];
					
					[newAA setValue:[singleLetter objectForKey:resName] forKey:@"letter"];   
					[newAA setValue:[fullName objectForKey:resName] forKey:@"name"];    
					//NSLog(@"%@",[fullName objectForKey:resName]);
					
				}
				[newAtom setValue:newAA forKey:@"aminoAcid"];				
				[[newAA mutableSetValueForKey:@"atoms"] addObject: newAtom];   
				[[newProtein mutableSetValueForKey:@"atoms"] addObject: newAtom];
				
				chain = [line substringWithRange:NSMakeRange(21, 1)];	
				[newAtom setValue:chain forKey:@"chain"];
				if ( strcmp([chain UTF8String],[prevChain UTF8String]) != 0 ){
					//NSLog(@"%s...%s...$i=%i",[chain UTF8String],[prevChain UTF8String], i);
					
					prevChain = [NSString stringWithUTF8String:[chain UTF8String]];
					newMonomer = [NSEntityDescription insertNewObjectForEntityForName:@"Monomer"
																					   inManagedObjectContext:managedObjectContext];
					[monomers addObject:newMonomer];
					[newMonomer setValue:newProtein forKey:@"multimer"];
					[newMonomer setValue:chain forKey:@"name"];
					[[newMonomer mutableSetValueForKey:@"aminoAcids"] addObject: newAA];
					[[newProtein mutableSetValueForKey:@"monomers"] addObject: newMonomer];
					
					
				}
				[[newMonomer mutableSetValueForKey:@"atoms"] addObject:	newAtom];	
				[newAA setValue:newMonomer forKey:@"monomer"];
				*/
				xchar = [line substringWithRange:NSMakeRange(26, 1)];										
				theScanner = [NSScanner scannerWithString:[line substringWithRange:NSMakeRange(31, 8)]];		//x
				[theScanner scanFloat:&x];
				
				theScanner = [NSScanner scannerWithString:[line substringWithRange:NSMakeRange(39, 8)]];		//y
				[theScanner scanFloat:&y];
				
				theScanner = [NSScanner scannerWithString:[line substringWithRange:NSMakeRange(48, 8)]];		//z
				[theScanner scanFloat:&z];
				/*
				if ([chain compare:@"A"]==0)
				{
					//NSLog(@"x %s", [chain UTF8String]);
					y += 20.0;
					x += 20.0;
				}
				if ([chain compare:@"C"]==0)
				{
					y -= 20.0;
					x += 20.0;
				}
				if ([chain compare:@"E"]==0)
				{
					x -= 20.0;
					y += 20.0;
					
				}
				if ([chain compare:@"F"]==0)
				{
					x -= 20.0;
					y -= 20.0;
				}
				
				*/
				
				[newAtom setValue:[NSNumber numberWithFloat:z]	forKey:@"z"];
				[newAtom setValue:[NSNumber numberWithFloat:y]	forKey:@"y"];
				[newAtom setValue:[NSNumber numberWithFloat:x]	forKey:@"x"];
				
				theScanner = [NSScanner scannerWithString:[line substringWithRange:NSMakeRange(55, 6)]];	
				[theScanner scanFloat:&occ];
				theScanner = [NSScanner scannerWithString:[line substringWithRange:NSMakeRange(60, 6)]];		//b
				[theScanner scanFloat:&b];
				
				char tempString[80];
				//%.3e %.3e %.3e   ATOM     10  N   MET A  18      29.900  21.000  28.089  1.00 12.56           N  
				sprintf(tempString, "ATOM     %.f %s %s %s  %.f      %.3f %.3f %.3f %.2f %.2f\n", aNumber, [aName UTF8String ], [resName UTF8String], [chain UTF8String], resNum, x, y, z, occ, b );
				[newAtom setValue:[NSString stringWithUTF8String:tempString] forKey:@"pdbLine"];
				
				fprintf(atomFile, "ATOM     %.f %s %s %s  %.f      %.3f %.3f %.3f %.2f %.2f\n", aNumber, [aName UTF8String ], [resName UTF8String], [chain UTF8String], resNum, x, y, z, occ, b );
				
				/*
				
				if ([chain compare:@"A"])
				{
					y += 0;
				}
				if ([chain compare:@"B"])
				{
					y -= 0;
				}
				if ([chain compare:@"C"])
				{
					x += 0;
				}
				if ([chain compare:@"D"])
				{
					x -= 0;
				}*/
				//fprintf(atomFile, "glVertex3f(%.3f, %.3f, %.3f);\n", x/100.0, y/100.0, z/100.0 );
			}
		}
	}
	
}
- (void) openFiles:(id)myFilePath
{
	myDocs = [myDocController documents];
	
	if ([myDocs count] == 0)
	{
		[myDocController openUntitledDocumentAndDisplay:YES error:nil];
	}
	
	
	
	highlightDocument = [myDocController currentDocument];
	managedObjectContext = [highlightDocument managedObjectContext];
	managedObjectModel = [highlightDocument managedObjectModel];
	
	
	
	[importerBusyIndicator startAnimation:self];
	//NSLog(@"MyFiles:%s",[[myFilePath objectAtIndex:0] UTF8String]); 
	//Now we have the path of the file
	pathExtension = [[[myFilePath objectAtIndex:0] lastPathComponent] pathExtension];
	
	if ([pathExtension compare:@"txt"] || [pathExtension compare:@"text"])
	{
		[[[myFilePath objectAtIndex:0]  stringByDeletingPathExtension] stringByAppendingPathExtension:@"fasta"];
	}
	pathExtension = [[[myFilePath objectAtIndex:0] lastPathComponent] pathExtension];
	
	if ([myDocs count] == 0)
	{
		[myDocController openUntitledDocumentAndDisplay:YES error:nil];
	}
	
	highlightDocument = [[NSDocumentController sharedDocumentController] currentDocument];
	
	//if we open file set the documents NSTextView
	//	NSLog(@"highlight Document at OpenFiles:%@",[highlightDocument description]);
	
	//	NSLog(@"You Docs=%@",[highlightDocument description]);
	
	//	[highlightDocument reportIn];
	managedObjectContext = [highlightDocument managedObjectContext];
	managedObjectModel = [highlightDocument managedObjectModel];
	
	//id newUCE = [NSEntityDescription insertNewObjectForEntityForName:@"UCE" inManagedObjectContext:managedObjectContext];
	
	
	//NSLog(@"last path component: %@",[[[myFilePath objectAtIndex:0] lastPathComponent] pathExtension]);
	if ([pathExtension compare: @"pdb" ] == 0)
	{
		NSLog(@"Protein path component");
		[self openProtein:myFilePath];
		
	}
	else
	{
		NSLog(@"DNA path component");
		
		[highlightDocument setSpeedDNATextView:[self openDNA:myFilePath]];
		[highlightDocument applySpeedometerSettings:self];
		
	}
	//NSPanel
	
	//[importerPanel setAutodisplay:YES];// makeMainWindow:self];
	[importerBusyIndicator stopAnimation:self];
	
}



- (IBAction)importAllData:sender
{
	id highlightDocument = [myDocController currentDocument];
	managedObjectContext = [highlightDocument managedObjectContext];
	managedObjectModel = [highlightDocument managedObjectModel];
	
	
	entities = [managedObjectModel entitiesByName];
	
	uceEntity = [entities valueForKey:@"UCE"];
	ncuEntity = [entities valueForKey:@"NCU"];
	cddEntity = [entities valueForKey:@"CDD"];
	blocksEntity = [entities valueForKey:@"Blocks"];
	clusterEntity = [entities valueForKey:@"Cluster"];
	proteinEntity = [entities valueForKey:@"Protein"];
	monomerEntity = [entities valueForKey:@"Monomer"];
	dnaEntity = [entities valueForKey:@"DNA"];
	mRNAEntity = [entities valueForKey:@"MRNA"];
	aminoacidEntity = [entities valueForKey:@"AminoAcid"];
	atomEntity = [entities valueForKey:@"Atom"];
	
	ncuSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	ncuSortDescriptors = [NSArray arrayWithObject: ncuSort];
	ncuFetch = [[NSFetchRequest alloc] init];
	[ncuFetch setEntity: ncuEntity];
	[ncuFetch setSortDescriptors: ncuSortDescriptors];
	
	cddSortName = [[NSSortDescriptor alloc] initWithKey:@"ncuID" ascending:YES];
	cddSortProtStart = [[NSSortDescriptor alloc] initWithKey:@"protStart" ascending:YES];
	cddSortDescriptors = [NSArray arrayWithObjects: cddSortName, cddSortProtStart,nil];
	cddFetch = [[NSFetchRequest alloc] init];
	[cddFetch setEntity: cddEntity];
	[cddFetch setSortDescriptors: cddSortDescriptors];
	
	uceSortName = [[NSSortDescriptor alloc] initWithKey:@"ncuID" ascending:YES];
	uceSortProtStart = [[NSSortDescriptor alloc] initWithKey:@"protStart" ascending:YES];
	uceSortDescriptors = [NSArray arrayWithObjects:uceSortName, uceSortProtStart,nil];
	uceFetch = [[NSFetchRequest alloc] init];
	[uceFetch setEntity: uceEntity];
	[uceFetch setSortDescriptors: uceSortDescriptors];
	
	blocksSortName = [[NSSortDescriptor alloc] initWithKey:@"ncuID" ascending:YES];
	blocksSortProtStart = [[NSSortDescriptor alloc] initWithKey:@"protStart" ascending:YES];
	blocksSortDescriptors = [NSArray arrayWithObjects: blocksSortName, blocksSortProtStart,nil];
	blocksFetch = [[NSFetchRequest alloc] init];
	[blocksFetch setEntity: blocksEntity];
	[blocksFetch setSortDescriptors: blocksSortDescriptors];
	
	clusterSort = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES];
	clusterSortDescriptors = [NSArray arrayWithObject: clusterSort];
	clusterFetch = [[NSFetchRequest alloc] init];
	[clusterFetch setEntity: clusterEntity];
	[clusterFetch setSortDescriptors: clusterSortDescriptors];
	
	proteinSort = [[NSSortDescriptor alloc] initWithKey:@"codeName" ascending:YES];
	proteinSortDescriptors = [NSArray arrayWithObject: proteinSort];
	proteinFetch = [[NSFetchRequest alloc] init];
	[proteinFetch setEntity: proteinEntity];
	[proteinFetch setSortDescriptors: proteinSortDescriptors];
	
	monomerSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	monomerSortDescriptors = [NSArray arrayWithObject: monomerSort];
	monomerFetch = [[NSFetchRequest alloc] init];
	[monomerFetch setEntity: monomerEntity];
	[monomerFetch setSortDescriptors: monomerSortDescriptors];
	
	dnaSort = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
	dnaSortDescriptors = [NSArray arrayWithObject: dnaSort];
	dnaFetch = [[NSFetchRequest alloc] init];
	[dnaFetch setEntity: dnaEntity];
	[dnaFetch setSortDescriptors: dnaSortDescriptors];
	
	mRNASort = [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];
	mRNASortDescriptors = [NSArray arrayWithObject: mRNASort];
	mRNAFetch = [[NSFetchRequest alloc] init];
	[mRNAFetch setEntity: mRNAEntity];
	[mRNAFetch setSortDescriptors: mRNASortDescriptors];
	
	aminoacidSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	aminoacidSortDescriptors = [NSArray arrayWithObject: aminoacidSort];
	aminoacidFetch = [[NSFetchRequest alloc] init];
	[aminoacidFetch setEntity: aminoacidEntity];
	[aminoacidFetch setSortDescriptors: aminoacidSortDescriptors];
	
	atomSort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
	atomSortDescriptors = [NSArray arrayWithObject: atomSort];
	atomFetch = [[NSFetchRequest alloc] init];
	[atomFetch setEntity: atomEntity];
	[atomFetch setSortDescriptors: atomSortDescriptors];
	
	
	managedObjectModel = [self managedObjectModel];
	managedObjectContext = [self managedObjectContext];
	[mySystemMessages setStringValue:@"Starting Import"];
	int i;
	NSScanner *theScanner;
	NSString *line,*sequenceString;
	NSMutableArray *ncuLines;
	NSMutableArray *blocksLines;
	NSMutableArray *cddLines;
	NSMutableArray *uceLines;
	char string [200];
	sequenceString  = @"";
	
	sequenceString = [[NSString alloc] init]; 					
	ncuLines = [[NSMutableArray alloc] init];					
	blocksLines = [[NSMutableArray alloc] init];					
	cddLines = [[NSMutableArray alloc] init];					
	uceLines = [[NSMutableArray alloc] init];					
	
	id ncuPath = [[ncuPathControl URL] path];
	id cddPath = [[cddPathControl URL] path];
	id ucePath = [[ucePathControl URL] path];
	id blocksPath = [[blocksPathControl URL] path];
	
	/*id ncuPath = [[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"data"] stringByAppendingPathComponent:@"test.fasta"];
	 id cddPath = [[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"data"] stringByAppendingPathComponent:@"test.cdd"];
	 id ucePath = [[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"data"] stringByAppendingPathComponent:@"test.uce"];
	 id blocksPath = [[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"data"] stringByAppendingPathComponent:@"test.blocks"];
	 */
	NSLog(@"%@",ncuPath);
	FILE * ncu		= fopen([ncuPath UTF8String],"r") ;
	FILE * blocks	= fopen([blocksPath UTF8String],"r") ;
	FILE * cdd		= fopen([cddPath UTF8String],"r") ;
	FILE * uce		= fopen([ucePath UTF8String],"r") ;
	
	id tabSet = [NSCharacterSet characterSetWithCharactersInString:@"\t"];
	
	//NCU FILE FIRST
	if (ncu == NULL) {
		fprintf(stderr,"***  Unable to open NCU file, returning NULL! *** \n");
	} else {
		char *sa;
		sa 	= fgets (string, 200, ncu);
		while( sa!= NULL)
		{
			[ncuLines addObject: [[NSString alloc] initWithUTF8String:sa]];			
			sa 	= fgets (string, 200, ncu);
		}
		fclose(ncu);
	}
	if (cdd == NULL) {
		fprintf(stderr,"***  Unable to open CDD file, returning NULL! *** \n");
	} else {
		char *sa;
		sa 	= fgets (string, 200, cdd);
		while( sa!= NULL)
		{
			[cddLines addObject: [[NSString alloc] initWithUTF8String:sa]];			
			sa 	= fgets (string, 200, cdd);
		}
		fclose(cdd);
	}
	if (blocks == NULL) {
		fprintf(stderr,"***  Unable to open BLOCKS file, returning NULL! *** \n");
	} else {
		char *sa;
		sa 	= fgets (string, 200, blocks);
		while( sa!= NULL)
		{
			[blocksLines addObject: [[NSString alloc] initWithUTF8String:sa]];			
			sa 	= fgets (string, 200, blocks);
		}
		fclose(blocks);
	}
	if (uce == NULL) {
		fprintf(stderr,"***  Unable to open UCE file, returning NULL! *** \n");
	} else {
		char *sa;
		sa 	= fgets (string, 200, uce);
		while( sa!= NULL)
		{
			[uceLines addObject: [[NSString alloc] initWithUTF8String:sa]];			
			sa 	= fgets (string, 200, uce);
		}
		fclose(uce);
	}
	[mySystemMessages setStringValue:@"Done Reading... Processing Data..."];
	id newNCU;
	id newNCU2;

	for ( i=0; i < [ncuLines count]; i++)
	{
		line = [ncuLines objectAtIndex:i];
		if ([line hasPrefix:@">"])  {
			newNCU = [NSEntityDescription insertNewObjectForEntityForName:@"NCU" inManagedObjectContext:managedObjectContext];
			[newNCU setValue:@"" forKey:@"proteinSequence"];
			[newNCU setValue:[line substringWithRange:NSMakeRange(1, 8)] forKey:@"name"];
			
			newNCU2 = [NSEntityDescription insertNewObjectForEntityForName:@"DNA" inManagedObjectContext:managedObjectContext];
			[newNCU2 setValue:[ncuLines objectAtIndex:i] forKey:@"title"];
			[newNCU2 setValue:@"" forKey:@"sequence"];
			
			
			//[newNCU2 setValue:newNCU forKey:@"ncu"];

		}
		else
		{
			[newNCU setValue:[[newNCU valueForKey:@"proteinSequence"] stringByAppendingString:[[line stringByReplacingOccurrencesOfString:@"\n" withString:@""] stringByReplacingOccurrencesOfString:@"*" withString:@"" ]] forKey:@"proteinSequence"];
			[newNCU2 setValue:[[newNCU2 valueForKey:@"sequence"] stringByAppendingString:[[line stringByReplacingOccurrencesOfString:@"\n" withString:@""] stringByReplacingOccurrencesOfString:@"*" withString:@""]] forKey:@"sequence"];
			
		}
	}
	
	NSArray *myNCU;/* = [managedObjectContext executeFetchRequest:ncuFetch error:nil];
	
	for (i=0;i<[myNCU count];i++)
	{
		newNCU2 = [NSEntityDescription insertNewObjectForEntityForName:@"DNA" inManagedObjectContext:managedObjectContext];
		[newNCU2 setValue:[newNCU valueForKey:@"proteinSequence"] forKey:@"sequence"];
		[newNCU2 setValue:[ncuLines objectAtIndex:i] forKey:@"title"];
	}*/
	
	id newBlocks;
	NSString * proteinID = @"";
	NSString * blocksID = @"";
	int blocksProtStart;
	int blocksProtEnd;
	
	
	for ( i=1; i < [blocksLines count]; i++)
	{
		line = [blocksLines objectAtIndex:i];
		theScanner = [NSScanner scannerWithString:line];
		
		while ([theScanner isAtEnd] == NO) {
			if ([theScanner scanUpToCharactersFromSet:tabSet intoString:&proteinID] &&
				[theScanner scanUpToCharactersFromSet:tabSet intoString:&blocksID] &&
				[theScanner scanInt:&blocksProtStart] &&
				[theScanner scanInt:&blocksProtEnd] ) {
			}
		}
		
		
		newBlocks = [NSEntityDescription insertNewObjectForEntityForName:@"Blocks" inManagedObjectContext:managedObjectContext];
		[newBlocks setValue:proteinID forKey:@"ncuID"];
		[newBlocks setValue:[NSNumber numberWithInt: blocksProtEnd] forKey:@"protEnd"];
		[newBlocks setValue:[NSNumber numberWithInt: blocksProtStart] forKey:@"protStart"];
		[newBlocks setValue:blocksID forKey:@"blocksID"];
	}
	
	id newCDD;
	NSString * cddID = @"";
	proteinID = @"";
	int cddProtStart;
	int cddProtEnd;
	
	proteinID = @"";
	
	for ( i=1; i < [cddLines count]; i++)
	{
		line = [cddLines objectAtIndex:i];
		theScanner = [NSScanner scannerWithString:line];
		
		while ([theScanner isAtEnd] == NO) {
			if ([theScanner scanUpToCharactersFromSet:tabSet intoString:&proteinID] &&
				[theScanner scanUpToCharactersFromSet:tabSet intoString:&cddID] &&
				[theScanner scanInt:&cddProtStart] &&
				[theScanner scanInt:&cddProtEnd] ) {
				//				NSLog(@"%@,%@,%i,%i",[proteinID description],[cddID description],cddProtStart,cddProtEnd);
			}
		}
		
		
		newCDD = [NSEntityDescription insertNewObjectForEntityForName:@"CDD" inManagedObjectContext:managedObjectContext];
		
		
		[newCDD setValue:proteinID forKey:@"ncuID"];
		[newCDD setValue:[NSNumber numberWithInt: cddProtEnd] forKey:@"protEnd"];
		[newCDD setValue:[NSNumber numberWithInt: cddProtStart] forKey:@"protStart"];
		[newCDD setValue:cddID forKey:@"cddID"];
	}
	
	id newUCE;
	NSString * uceSequence = @"";
	NSString * ucePeptide = @"";
	int uceProtStart;
	int uceProtEnd;
	int uceID;
	
	proteinID = @"";
	
	for ( i=1; i < [uceLines count]; i++)
	{
		line = [uceLines objectAtIndex:i];
		theScanner = [NSScanner scannerWithString:line];
		
		while ([theScanner isAtEnd] == NO) {
			if ([theScanner scanUpToCharactersFromSet:tabSet intoString:&proteinID] &&
				[theScanner scanInt:&uceProtStart] &&
				[theScanner scanInt:&uceProtEnd] &&
				[theScanner scanInt:&uceID] &&
				[theScanner scanUpToCharactersFromSet:tabSet intoString:&uceSequence] &&
				[theScanner scanUpToCharactersFromSet:tabSet intoString:&ucePeptide]	) {
				//NSLog(@"%@,%i,%i,%i,%@,%@",[proteinID description],uceID,uceProtStart,uceProtEnd,[uceSequence description],[ucePeptide description]);
			}
		}
		
		newUCE = [NSEntityDescription insertNewObjectForEntityForName:@"UCE" inManagedObjectContext:managedObjectContext];
		
		[newUCE setValue:proteinID forKey:@"ncuID"];
		[newUCE setValue:[NSNumber numberWithInt: uceProtEnd] forKey:@"protEnd"];
		[newUCE setValue:[NSNumber numberWithInt: uceProtStart] forKey:@"protStart"];
		[newUCE setValue:[NSNumber numberWithInt: uceID] forKey:@"uceID"];
		[newUCE setValue:uceSequence forKey:@"uceDNASequence"];
		[newUCE setValue:ucePeptide forKey:@"ucePeptideSequence"];
		//NSLog(@"%@",[newUCE description]);
	}
	
	
	//predicate = [NSPredicate predicateWithFormat:@"name like[c] %@",[myNCU name] ];
	//NSArray * myBlocks = [managedObjectContext executeFetchRequest:blocksFetch error:nil];
	//NSArray * myCDD = [managedObjectContext executeFetchRequest:cddFetch error:nil];
	//NSArray * myUCE = [managedObjectContext executeFetchRequest:uceFetch error:nil];
	//NSLog(@"YouArray=%i,%i,%i,%i",[myNCU count],[myBlocks count],[myCDD count],[myUCE count]);
	
	int cddNum=0,uceNum=0,blocksNum=0;
	int j;
	
	//predicate = [NSPredicate predicateWithFormat:@"ncuID like[c] %@",[tempNCU name] ];
	
	
	[ncuFetch setPredicate:nil];
	[blocksFetch setPredicate:nil];
	[cddFetch setPredicate:nil];
	[uceFetch setPredicate:nil];
	//id myNCU;
	//id myBlocks;
	//id myCDD;
	//id myUCE;
	
	myNCU = [managedObjectContext executeFetchRequest:ncuFetch error:nil];
	NSArray * myBlocks = [managedObjectContext executeFetchRequest:blocksFetch error:nil];
	NSArray * myCDD = [managedObjectContext executeFetchRequest:cddFetch error:nil];
	NSArray * myUCE = [managedObjectContext executeFetchRequest:uceFetch error:nil];
	
//	NSLog(@"your de%@",[myNCU description]);
	int finBlock=0;
	int finCDD=0;
	int finUCE=0;
	
	id cluster;
	
	[mySystemMessages setStringValue:@"Creating Relationships..."];
	NSLog(@"Creating Relationships....");
	
	for (j=0; j<[myNCU count]; j++)
	{
		id holder;
		id tempNCU = [myNCU objectAtIndex:j];
		//[mySystemMessages setStringValue:[[mySystemMessages stringValue] stringByAppendingString:[[myNCU objectAtIndex:j] valueForKey:@"ncuID"]]];
		//NSLog(@"%@",[[myNCU objectAtIndex:j]description]);		
		
		cluster = [NSEntityDescription insertNewObjectForEntityForName:@"Cluster" inManagedObjectContext:managedObjectContext];
		//CLUSTER --> NCU
		id temp = [cluster mutableSetValueForKey:@"ncus"];
		[temp addObject:tempNCU];
		[cluster setValue:temp forKey:@"ncus"];
		//NCU -->> CLUSTER
		temp = [tempNCU mutableSetValueForKey:@"clusters"];
		[temp addObject:cluster];
		[tempNCU setValue:temp forKey:@"clusters"];
		
		[cluster setValue:[NSNumber numberWithInt:0]	
							   forKey:@"protStart" ];
		[cluster setValue:[NSNumber numberWithInt:0]	
									 forKey:@"protEnd" ];
		
		[cluster setValue:[NSNumber numberWithInt:1] forKey:@"name" ];
		
		id objectArray = [[NSMutableArray alloc] init];
		if ( finBlock == 0 ){
			
			if ( [[[myBlocks objectAtIndex:blocksNum] valueForKey:@"ncuID"] isEqualToString:[tempNCU name]])
			{
				while ([[[myBlocks objectAtIndex:blocksNum] valueForKey:@"ncuID"] isEqualToString:[tempNCU name]])
				{
					[objectArray addObject:[myBlocks objectAtIndex:blocksNum]];
					holder = [[myBlocks objectAtIndex:blocksNum] mutableSetValueForKey:@"ncus"];
					[holder addObject:tempNCU];
					[[myBlocks objectAtIndex:blocksNum] setValue:holder forKey:@"ncus"];
					
					holder = [tempNCU mutableSetValueForKey:@"blocks"];
					[holder addObject:[myBlocks objectAtIndex:blocksNum]];
					[tempNCU setValue:holder forKey:@"blocks"];
					
					[tempNCU setValue:[NSNumber numberWithInt:[[tempNCU valueForKey:@"blocksCount"] intValue] +1] forKey:@"blocksCount"];
					
					//if (blocksNum < [myBlocks count])
					blocksNum++;
					//NSLog(@"Blocks=%i,%i",blocksNum, [myBlocks count]);
					
					if (blocksNum == [myBlocks count])
					{
						finBlock = 1;
						break;
					}
				}
				
			}
		}
		
		if ( finCDD == 0 ) {
			
			if ( [[[myCDD objectAtIndex:cddNum] valueForKey:@"ncuID"] isEqualToString:[tempNCU name]])
			{
				while([[[myCDD objectAtIndex:cddNum] valueForKey:@"ncuID"] isEqualToString:[tempNCU name]])	
				{
					[objectArray addObject:[myCDD objectAtIndex:cddNum]];
					holder = [[myCDD objectAtIndex:cddNum] mutableSetValueForKey:@"ncus"];
					[ holder addObject:tempNCU ];
					[[myCDD objectAtIndex:cddNum] setValue:holder forKey:@"ncus"];
					
					holder = [tempNCU mutableSetValueForKey:@"cdds"];
					[holder addObject:[myCDD objectAtIndex:cddNum]];
					[tempNCU setValue:holder forKey:@"cdds"];
					
					[tempNCU setValue:[NSNumber numberWithInt:[[tempNCU valueForKey:@"cddCount"] intValue] +1] forKey:@"cddCount"];
					
					cddNum++;
					if (cddNum == [myCDD count])
					{
						finCDD = 1;
						break;
					}
				}
				
			}
		}
		if ( finUCE == 0 ){
			
			
			if ( [[[myUCE objectAtIndex:uceNum] valueForKey:@"ncuID"] isEqualToString:[tempNCU name]])
			{
				while ([[[myUCE objectAtIndex:uceNum] valueForKey:@"ncuID"] isEqualToString:[tempNCU name]])
				{
					[objectArray addObject:[myUCE objectAtIndex:uceNum]];
					holder = [[myUCE objectAtIndex:uceNum] mutableSetValueForKey:@"ncus"];
					[holder addObject:tempNCU];
					[[myUCE objectAtIndex:uceNum] setValue:holder forKey:@"ncus"];
					
					holder = [tempNCU mutableSetValueForKey:@"uces"];
					[holder addObject:[myUCE objectAtIndex:uceNum]];
					[tempNCU setValue:holder forKey:@"uces"];
					
					[tempNCU setValue:[NSNumber numberWithInt:[[tempNCU valueForKey:@"uceCount"] intValue] +1] forKey:@"uceCount"];
					
					uceNum++;
					if (uceNum == [myUCE count])
					{
						finUCE = 1;
						break;
					}
				}
			}
		}
		if ([objectArray count] > 0)
		{
			[objectArray sortedArrayUsingDescriptors:cddSortDescriptors];
			
			for (i=0; i< [objectArray count]; i++)
			{
				// Loop through all the items in the array of objects adding according to protStart and depending on the entity type...
				if ([[cluster valueForKey:@"protEnd"] intValue] == 0)
				{
					[cluster setValue:[[objectArray objectAtIndex:i] valueForKey:@"protStart"]
																			forKey:@"protStart"];
					[cluster setValue:[[objectArray objectAtIndex:i] valueForKey:@"protEnd"]
																			forKey:@"protEnd"];				
				}
				else{
					if ([[cluster valueForKey:@"protEnd"] intValue] > [[[objectArray objectAtIndex:i] valueForKey:@"protStart"] intValue])
					{
						if ([[[objectArray objectAtIndex:i] entity] isKindOfEntity:blocksEntity])
						{
							id temp1 = [cluster mutableSetValueForKey:@"blocks"];
							[temp1 addObject:[objectArray objectAtIndex:i]];
							[cluster setValue:temp1 forKey:@"blocks"];
						}
						if ([[[objectArray objectAtIndex:i] entity] isKindOfEntity:uceEntity])
						{
							id temp1 = [cluster mutableSetValueForKey:@"uces"];
							[temp1 addObject:[objectArray objectAtIndex:i]];
							[cluster setValue:temp1 forKey:@"uces"];
						}
						if ([[[objectArray objectAtIndex:i] entity] isKindOfEntity:cddEntity])
						{
							id temp1 = [cluster mutableSetValueForKey:@"cdds"];
							[temp1 addObject:[objectArray objectAtIndex:i]];
							[cluster setValue:temp1 forKey:@"cdds"];
						}
						
					}
					else
					{	
						int tempClusterNum = [[cluster valueForKey:@"name"] intValue];
						cluster = [NSEntityDescription insertNewObjectForEntityForName:@"Cluster" inManagedObjectContext:managedObjectContext];
						//CLUSTER --> NCU
						id temp = [cluster mutableSetValueForKey:@"ncus"];
						[temp addObject:tempNCU];
						[cluster setValue:temp forKey:@"ncus"];
						//NCU -->> CLUSTER
						temp = [tempNCU mutableSetValueForKey:@"clusters"];
						[temp addObject:cluster];
						[tempNCU setValue:temp forKey:@"clusters"];
						
						if ([[[objectArray objectAtIndex:i] entity] isKindOfEntity:blocksEntity])
						{
							id temp1 = [cluster mutableSetValueForKey:@"blocks"];
							[temp1 addObject:[objectArray objectAtIndex:i]];
							[cluster setValue:temp1 forKey:@"blocks"];
						}
						if ([[[objectArray objectAtIndex:i] entity] isKindOfEntity:uceEntity])
						{
							id temp1 = [cluster mutableSetValueForKey:@"uces"];
							[temp1 addObject:[objectArray objectAtIndex:i]];
							[cluster setValue:temp1 forKey:@"uces"];
						}
						if ([[[objectArray objectAtIndex:i] entity] isKindOfEntity:cddEntity])
						{
							id temp1 = [cluster mutableSetValueForKey:@"cdds"];
							[temp1 addObject:[objectArray objectAtIndex:i]];
							[cluster setValue:temp1 forKey:@"cdds"];
						}
						
						[cluster setValue:[NSNumber numberWithInt:tempClusterNum+1] forKey:@"name" ];
						[cluster setValue:[[objectArray objectAtIndex:i] valueForKey:@"protStart"]
																	forKey:@"protStart"];
						[cluster setValue:[[objectArray objectAtIndex:i] valueForKey:@"protEnd"]
																	forKey:@"protEnd"];	
						
					}
				}
			}
		}
		
		/*if ([[Y entity] isKindOfEntity:blocksEntity])
		 {
		 blocksNum++;
		 temp = [myCluster mutableSetValueForKey:@"blocks"];
		 [temp addObject:Y];
		 [myCluster setValue:temp forKey:@"blocks"];
		 
		 temp = [Y mutableSetValueForKey:@"cluster"];
		 [temp addObject:myCluster];
		 [Y setValue:temp forKey:@"cluster"];
		 }
		 if ([[Y entity] isKindOfEntity:uceEntity])
		 {	
		 uceNum++;
		 temp = [myCluster mutableSetValueForKey:@"uces"];
		 [temp addObject:Y];
		 [myCluster setValue:temp forKey:@"uces"];
		 
		 temp = [Y mutableSetValueForKey:@"cluster"];
		 [temp addObject:myCluster];
		 [Y setValue:temp forKey:@"cluster"];
		 }
		 if ([[Y entity] isKindOfEntity:cddEntity])
		 {	
		 cddNum++;	
		 temp = [myCluster mutableSetValueForKey:@"cdds"];
		 [temp addObject:Y];
		 [myCluster setValue:temp forKey:@"cdds"];
		 
		 temp = [Y mutableSetValueForKey:@"cluster"];
		 [temp addObject:myCluster];
		 [Y setValue:temp forKey:@"cluster"];				
		 }*/
		
		
	}
	[mySystemMessages setStringValue:@"Finished!"];
	
	NSLog(@"Finished");
	
	
	
	
	//	id ncuUCESort = [[NSSortDescriptor alloc] initWithKey:@"uceCount" ascending:NO];
	//	id ncuUCESortDescriptors = [NSArray arrayWithObject: ncuUCESort];
	//	id ncuUCEFetch = [[NSFetchRequest alloc] init];
	//	[ncuUCEFetch setEntity: ncuEntity];
	//	[ncuUCEFetch setSortDescriptors: ncuUCESortDescriptors];
	
	//	predicate = [NSPredicate predicateWithFormat:@"name like[c] %@",@"NCU11168" ];
	//	[ncuFetch setPredicate:predicate];
	//	myNCU = [managedObjectContext executeFetchRequest:ncuUCEFetch error:nil];
	//	for( i=0; i<50;i++){	
	//			NSLog(@"%@",[[myNCU objectAtIndex:i] description]);
	//	}						   
	
	//OPEN A FILE AND SPIT SHIT OUT.
	/*
	 NSString *myString = @"";
	 
	 NSError *error;
	 int k;
	 int p;
	 
	 //	for (p=0; p<([myNCU count]%100); p++)
	 //	{
	 //		NSLog(@"%i",p);
	 for (j=9000; j<[myNCU count]; j++)
	 {
	 //NAME OF NCU
	 if (j%100 == 0) NSLog(@"%i",j);
	 myString = [[myString stringByAppendingString:[[myNCU objectAtIndex:j] valueForKey:@"name"]] stringByAppendingString:@"\n"];
	 //LOOP THROUGH ALL CLUSTERS
	 id tempClusters = [[[[myNCU objectAtIndex:j] mutableSetValueForKey:@"clusters"] allObjects] sortedArrayUsingDescriptors:ncuSortDescriptors];
	 for( i=0; i<[tempClusters count]; i++)
	 {
	 myString = [myString stringByAppendingString:@"\tCluster #"];
	 myString = [[myString stringByAppendingString:[[[tempClusters objectAtIndex:i] valueForKey:@"name"] stringValue]] stringByAppendingString:@"\n"];	
	 //myString = [[myString stringByAppendingString:[[tempClusters objectAtIndex:i] description]] stringByAppendingString:@"\n"];
	 
	 id tempBlocks = [[[[tempClusters objectAtIndex:i] mutableSetValueForKey:@"blocks"] allObjects] sortedArrayUsingDescriptors:blocksSortDescriptors];
	 id tempCDDs = [[[[myNCU objectAtIndex:j] mutableSetValueForKey:@"cdds"] allObjects] sortedArrayUsingDescriptors:cddSortDescriptors];
	 id tempUCEs = [[[[myNCU objectAtIndex:j] mutableSetValueForKey:@"uces"] allObjects] sortedArrayUsingDescriptors:uceSortDescriptors];
	 
	 for ( k=0; k<[tempBlocks count]; k++)
	 {
	 myString = [myString stringByAppendingString:@"\t\tBlock #"];
	 myString = [[myString stringByAppendingString:[[tempBlocks objectAtIndex:k] valueForKey:@"blocksID"]] stringByAppendingString:@"\n"];	
	 }
	 
	 for ( k=0; k<[tempCDDs count]; k++)
	 {
	 myString = [myString stringByAppendingString:@"\t\tCDD #"];
	 myString = [[myString stringByAppendingString:[[tempCDDs objectAtIndex:k] valueForKey:@"cddID"]] stringByAppendingString:@"\n"];	
	 }
	 
	 for ( k=0; k<[tempUCEs count]; k++)
	 {
	 myString = [myString stringByAppendingString:@"\t\tUCE #"];
	 myString = [[myString stringByAppendingString:[[[tempUCEs objectAtIndex:k] valueForKey:@"uceID"] stringValue]] stringByAppendingString:@"\n"];	
	 }
	 }
	 
	 }
	 
	 
	 [myString writeToFile:[NSString stringWithFormat:@"./results9000-%i",[myNCU count]] atomically:YES encoding:NSUTF8StringEncoding error:&error];
	 
	 //}*/
}




@end
/*
 CODE SNIPPETS THAT MANIPULATE FILES REALLY WELL
 
 
 
 NSDictionary *fileAttributes = [fileManager fileAttributesAtPath:path traverseLink:YES];
 if (fileAttributes != nil) {
 // Get file's modification date.
 NSDate *fileModificationDate = [fileAttributes objectForKey:NSFileModificationDate];
 if ([fileModificationDate compare:[asset dateLastUpdated]] == NSOrderedDescending) {
 [assetsChanged addObject:asset];
 }
 }
 
 - (NSArray *)findAssetFilesInRootURL {
 NSString *rootPath = [[self rootURL] path];
 NSFileManager *fileManager = [NSFileManager defaultManager];
 NSArray *possibleAssetFiles = [fileManager directoryContentsAtPath:rootPath];
 NSArray *supportedAssetFileTypes = [ImageAsset fileTypes];
 NSMutableArray *assetFiles = [NSMutableArray array];
 
 for (NSString *filename in possibleAssetFiles) {
 // (In a real-world application, if we have a filename with no extension, we should be prepared to check the file's HFS type code or other identifying metadata here.)
 if ([supportedAssetFileTypes containsObject:[filename pathExtension]]) {
 [assetFiles addObject:filename];
 }
 }
 return assetFiles;
 }
 */
